package com.rightsidetech.commom.utils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author fish
 * @company RightSide
 * @create 2017-03-31 下午5:39
 */
public class BeanValidator {
    /**
     * 验证某个bean的参数
     *
     * @param object 被校验的参数
     * //@throws ValidationException 如果参数校验不成功则抛出此异常
     */
    public static <T> ConstraintViolation validate(T object) {
        //获得验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object);
        //如果有验证信息，则将第一个取出来包装成异常返回
        if (!constraintViolations.isEmpty()){
            for (ConstraintViolation<T> constraintViolation : constraintViolations){
                return constraintViolation;
            }
        }
//        ConstraintViolation<T> constraintViolation = getFirst(constraintViolations, null);
//        if (constraintViolation != null) {
//            throw new ValidationException(constraintViolation);
//        }
        return null;
    }

    /** 验证失败将抛出异常 */
    public static <T> ConstraintViolation validateGroup(T object, Class<?>... groups) {
        //获得验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object,groups);
        //如果有验证信息，则将第一个取出来包装成异常返回
        if (!constraintViolations.isEmpty()){
            for (ConstraintViolation<T> constraintViolation : constraintViolations){
                return constraintViolation;
            }
        }
        return null;
//        String msg = "validate failure on object:" + object.getClass().getSimpleName();
//        if (!constraintViolations.isEmpty()) {
//            throw new ConstraintViolationException(msg, constraintViolations);
//        }
    }
}
